import { DatePicker, Form, Input, Modal, Select } from "antd";
import dayjs from "dayjs";
import { useTranslation } from "react-i18next";

interface TaskModalProps {
	open: boolean;
	title: string;
	initialValues?: TaskItem;
	onOk: (values: TaskItem) => void;
	onCancel: () => void;
}

interface TaskItem {
	id?: string;
	title: string;
	status: "pending" | "in_progress" | "completed";
	priority: "low" | "medium" | "high";
	assignee: string;
	dueDate: string;
}

export default function TaskModal({
	open,
	title,
	initialValues,
	onOk,
	onCancel,
}: TaskModalProps) {
	const [form] = Form.useForm();
	const { t } = useTranslation();

	const handleOk = async () => {
		try {
			const values = await form.validateFields();
			onOk({
				...initialValues,
				...values,
				dueDate: values.dueDate.format("YYYY-MM-DD"),
			});
			form.resetFields();
		} catch (error) {
			console.error("Validation failed:", error);
		}
	};

	const handleCancel = () => {
		form.resetFields();
		onCancel();
	};

	return (
		<Modal
			open={open}
			title={title}
			onOk={handleOk}
			onCancel={handleCancel}
			destroyOnClose
		>
			<Form
				form={form}
				layout="vertical"
				initialValues={{
					...initialValues,
					dueDate: initialValues?.dueDate
						? dayjs(initialValues.dueDate)
						: undefined,
				}}
			>
				<Form.Item
					name="title"
					label="Title"
					rules={[{ required: true, message: "Please input task title!" }]}
				>
					<Input />
				</Form.Item>

				<Form.Item
					name="status"
					label="Status"
					rules={[{ required: true, message: "Please select task status!" }]}
				>
					<Select>
						<Select.Option value="pending">Pending</Select.Option>
						<Select.Option value="in_progress">In Progress</Select.Option>
						<Select.Option value="completed">Completed</Select.Option>
					</Select>
				</Form.Item>

				<Form.Item
					name="priority"
					label="Priority"
					rules={[{ required: true, message: "Please select task priority!" }]}
				>
					<Select>
						<Select.Option value="low">Low</Select.Option>
						<Select.Option value="medium">Medium</Select.Option>
						<Select.Option value="high">High</Select.Option>
					</Select>
				</Form.Item>

				<Form.Item
					name="assignee"
					label="Assignee"
					rules={[{ required: true, message: "Please input assignee name!" }]}
				>
					<Input />
				</Form.Item>

				<Form.Item
					name="dueDate"
					label="Due Date"
					rules={[{ required: true, message: "Please select due date!" }]}
				>
					<DatePicker className="w-full" />
				</Form.Item>
			</Form>
		</Modal>
	);
}
